Skip to main content

Leetcode 347

· One min read
Junhe Chen
class Solution {
public int[] topKFrequent(int[] nums, int k) {
// don't think quicksort is acutally good here
int[] res = new int[k];
HashMap<Integer,Integer> count = new HashMap<>();
for(int n : nums){
if(count.containsKey(n)){
count.put(n,count.get(n) + 1);
}else{
count.put(n,1);
}
}
PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> {return b[1] - a[1];});
for(int key : count.keySet()){
pq.add(new int[]{key,count.get(key)});
}
for(int i = 0; i < k; i ++){
res[i] = pq.poll()[0];
}
return res;
}
}